# The MIT License (MIT)
#
# Copyright (c) 2013 Vladimir Jovic
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


CXX=        g++
CXXFLAGS=   -Wall -W -Wall -Wextra -std=c++11 -pedantic -fPIC


TARGET_DIR=./bin
FUSED_GTEST=/usr/src


DEBUG_BUILD?=0
ifeq ($(DEBUG_BUILD), 1)
	CXXFLAGS+=-g
	TARGET_SUFIX=_debug
else
	CXXFLAGS+=-O3
	TARGET_SUFIX=
endif

HEADERS=$(wildcard code/*.hpp)
SOURCES=$(wildcard code/*.cpp)

# includes
INCLUDES=-I. -I./code/ -I/usr/include/
INCLUDES+=$(shell pkg-config --cflags Qt5Gui Qt5OpenGL)

# qt resources
QT_RESOURCES=./resources/resources.qrc

# libraries to link
LIBS=$(shell pkg-config --libs Qt5Gui Qt5OpenGL)

# objects directory, and object files
OBJS=$(patsubst %.cpp, $(OBJS_DIR)/%.src.o, $(notdir $(SOURCES)))
OBJS+=$(patsubst %.hpp, $(OBJS_DIR)/%.moc.o, $(notdir $(HEADERS)))
OBJS+=$(OBJS_DIR)/resources.rcc.o

UNITTESTS_BUILD?=0
ifeq ($(UNITTESTS_BUILD), 1)
	CXXFLAGS+=-pthread

	TARGET_PREFIX=unittests
	TARGET=$(TARGET_DIR)/unittests_runner

	SOURCES+=$(wildcard code/unittests/*.cpp)
	INCLUDES+=-I$(FUSED_GTEST)/gtest
	INCLUDES+=$(shell pkg-config --cflags QtTest)
	LIBS+=$(shell pkg-config --libs QtTest)
else
	SOURCES+=code/app/main.cpp
	TARGET_PREFIX=app
	TARGET=$(TARGET_DIR)/app_runner
endif

VPATH=$(sort $(dir $(SOURCES)))

OBJS_DIR=$(TARGET_DIR)/$(TARGET_PREFIX)$(TARGET_SUFIX)


all : $(TARGET)


clean :
	@rm -rf bin/*



$(OBJS_DIR)/%.moc.o : %.hpp | $(OBJS_DIR)
	moc $< | $(CXX) -c $(CXXFLAGS) $(INCLUDES) -xc++ -o $@ -

$(OBJS_DIR)/%.src.o : %.cpp | $(OBJS_DIR)
	$(CXX) -c $(CXXFLAGS) $(INCLUDES) $< -o $@

$(OBJS_DIR)/%.rcc.o : $(QT_RESOURCES) | $(OBJS_DIR)
	rcc $< | $(CXX) -c $(CXXFLAGS) $(INCLUDES) -xc++ -o $@ -

$(OBJS_DIR) :
	@mkdir -p $(OBJS_DIR)

$(TARGET) : $(OBJS)
	$(CXX) -o $(TARGET) $(CXXFLAGS) $(INCLUDES) $(OBJS) $(LIBS)


# headers dependencies
depend: .depend

.depend: $(SRCS)
	rm -f ./.depend
	$(CXX) $(CXXFLAGS) $(INCLUDES) -MM $^ > ./.depend;

include .depend
